package tr.edu.metu.is550.isell.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import tr.edu.metu.is550.isell.R;
import tr.edu.metu.is550.isell.dialog.AddCommentDialog;
import tr.edu.metu.is550.isell.utils.CryptoUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class PropertyDetailActivity extends Activity {
    

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.property_detail);
        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

        final Long propertyId = (Long) getIntent().getExtras().get("propertyId");
        retrievePropertyDetails(sp, propertyId);
        Button btnComments = (Button) findViewById(R.id.btnComments);
        Button btnAddPhoto = (Button) findViewById(R.id.btnAddPhoto);

        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = defaultSharedPreferences.edit();
        editor.putString("propertyIdDetail", propertyId.toString());
        editor.apply();


        btnComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), ListCommentsActivity.class);
                myIntent.putExtra("propertyId", propertyId.toString());
                startActivity(myIntent);
            }
        });

        btnAddPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), ImageUpload.class);
                myIntent.putExtra("propertyId", propertyId.toString());
                startActivity(myIntent);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.property_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        AddCommentDialog dialog = new AddCommentDialog(this, true, new DialogInterface.OnCancelListener() {
//            @Override
//            public void onCancel(DialogInterface dialogInterface) {
//
//            }
//        });
//        dialog.show();
//        return true;
        final Long propertyId = (Long) getIntent().getExtras().get("propertyId");
        Intent addCommentIntent = new Intent(this, AddCommentActivity.class);
        addCommentIntent.putExtra("propertyId", propertyId.toString());
        addCommentIntent.putExtra("value", "old value to edit");
        this.startActivityForResult(addCommentIntent, 1);

        return true;


    }

    private InputStream getImageStream(SharedPreferences sp, Long propertyId) {
        InputStream is = null;
        try {
            String serverURL = sp.getString("pref_dialog", "NULL");
            String uri = serverURL + "/property/".concat(propertyId.toString()).concat("/map");
            HttpGet httpGet = new HttpGet(uri);
            DefaultHttpClient client = new DefaultHttpClient();
            httpGet.setHeader("Authorization", "ISell " + CryptoUtils.encryptAndBase64Encode(getApplicationContext(), sp.getString("userName", "") + ":" + sp.getString("password", "")));
            HttpResponse response = client.execute(httpGet);
            is = response.getEntity().getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;
    }

    private void retrievePropertyDetails(SharedPreferences sp, Long propertyId) {
        try {
            String serverURL = sp.getString("pref_dialog", "NULL");
            DefaultHttpClient client = new DefaultHttpClient();
            String uri = serverURL + "/property/".concat(propertyId.toString());

            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Content-Type", "application/json");
            httpGet.setHeader("Accept", "application/json");
            httpGet.setHeader("Authorization", "ISell " + CryptoUtils.encryptAndBase64Encode(getApplicationContext(), sp.getString("userName", "") + ":" + sp.getString("password", "")));

            HttpResponse response = client.execute(httpGet);
            if (HttpStatus.SC_UNAUTHORIZED == response.getStatusLine().getStatusCode()) {
                Toast.makeText(getApplicationContext(), "Not Authorized!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                throw new RuntimeException("An exception occured during get property details!");
            }

            HttpEntity entity = response.getEntity();
            String result = convertStreamToString(entity.getContent());
            JSONObject jsonObject = new JSONObject(result);
            JSONObject property = jsonObject.getJSONObject("property");

            ((TextView) findViewById(R.id.txtTitle)).setText(property.getString("title"));
            ((TextView) findViewById(R.id.txtDetail)).setText(property.getString("details"));
            ((TextView) findViewById(R.id.txtPrice)).setText(property.getString("price"));
            ((TextView) findViewById(R.id.txtNumberOfRooms)).setText(property.getString("numberOfRooms"));
            ((TextView) findViewById(R.id.txtAddress)).setText(property.getString("address"));
            ((TextView) findViewById(R.id.txtAdvertiserEmail)).setText(property.getString("advirtiserEmail"));
            ((TextView) findViewById(R.id.txtAdvertiserPhone)).setText(property.getString("advirtiserPhone"));
            ((TextView) findViewById(R.id.txtAdvertisedBy)).setText(property.getString("advirtiserName") + " " + property.getString("advirtiserSurname"));
            ((TextView) findViewById(R.id.txtPropertyType)).setText(property.getInt("propertyType") == 1 ? "Flat" : "House");
            ((TextView) findViewById(R.id.txtAdType)).setText(property.getInt("adtype") == 1 ? "Sale" : "Rental");

            ImageView map = (ImageView) findViewById(R.id.imgMap);
            InputStream imageStream = getImageStream(sp, propertyId);

            if (imageStream != null)
                map.setImageBitmap(BitmapFactory.decodeStream(imageStream));


        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    private static String convertStreamToString(InputStream is) {
        /*
        * To convert the InputStream to String we use the BufferedReader.readLine()
        * method. We iterate until the BufferedReader return null which means
        * there's no more data to read. Each line will appended to a StringBuilder
        * and returned as String.
        */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                try {
                    String value = data.getStringExtra("value");
//                    Toast.makeText(getApplicationContext(), "  TEXT MESSAGE TO BER PROCESSED    ONACTIVITY RESULT  " +value, Toast.LENGTH_SHORT).show();
                    if (value != null && value.length() > 0) {
                        addComment(value);
                    }

                } catch (Exception e) {
                }
    }

        private void addComment(String value) {

               try {
                    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
                    String serverURL = sp.getString("pref_dialog", "NULL");
                    DefaultHttpClient client = new DefaultHttpClient();

                    JSONObject commentMsg = new JSONObject();
                    JSONObject detail = new JSONObject();
                    detail.put("comment", value);
                    detail.put("user", "alpaye"); // TODO user to be given
                    commentMsg.put("comment", detail);

                    String propertyId = sp.getString("propertyIdDetail","");
                    // Toast.makeText(getApplicationContext(), "PROPERTY ID3 .... " + propertyId, Toast.LENGTH_SHORT).show();
                    String uri = serverURL + "/property/" + propertyId + "/comment";

                    // Toast.makeText(getApplicationContext(), "IURI   URI   .... "+ uri, Toast.LENGTH_SHORT).show();
                    HttpPost httpPost = new HttpPost(uri);
                    httpPost.setHeader("Content-Type", "application/json");
                    httpPost.setHeader("Accept", "application/json");
                    httpPost.setHeader("Authorization", "ISell " + CryptoUtils.encryptAndBase64Encode(getApplicationContext(), sp.getString("userName", "") + ":" + sp.getString("password", "")));
                    httpPost.setEntity(new ByteArrayEntity(commentMsg.toString().getBytes()));

                    HttpResponse response = client.execute(httpPost);

                    int statusCode = response.getStatusLine().getStatusCode();

                    if (HttpStatus.SC_CREATED == statusCode) {
                        Toast.makeText(getApplicationContext(), "Comment Added", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (HttpStatus.SC_UNAUTHORIZED == statusCode) {
                        Toast.makeText(getApplicationContext(), "Not Authorized!", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    throw new RuntimeException("An exception occured during adding comment !");

                } catch (Exception e) {
                    Toast toast = Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT);
                    toast.show();
                }

    }

}
